export type callback<K, V> = (key: K, val: V) => void;

export class Dictionary<K, V> {
  private keys: K[] = [];
  private vals: V[] = [];

  // 属性访问器：类似于vue的计算属性
  get size() {
    return this.keys.length;
  }

  set(key: K, val: V) {
    const index = this.keys.indexOf(key);
    if (index === -1) {
      this.keys.push(key);
      this.vals.push(val);
    } else {
      this.vals[index] = val;
    }

    console.log(this.keys);
    console.log(this.vals);
  }

  get(key: K) {
    const index = this.keys.indexOf(key);
    if (index !== -1) {
      return this.vals[index];
    }
  }

  forEach(cb: callback<K, V>) {
    this.keys.forEach((key, i) => cb(key, this.vals[i]));
  }

  has(key: K) {
    return this.keys.includes(key);
  }

  delete(key: K) {
    const index = this.keys.indexOf(key);
    if (index !== -1) {
      this.keys.splice(index, 1);
      this.vals.splice(index, 1);
    }
  }
}
